

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def right_side_view(root):
    """
    二叉树右视图：层序遍历时记录每层最后一个节点
    root：二叉树根节点
    """
    if not root:
        return []
    from collections import deque
    queue = deque([root])
    result = []
    while queue:
        level_size = len(queue)
        for i in range(level_size):
            node = queue.popleft()
            # 记录每层最后一个节点（右视图节点）
            if i == level_size - 1:
                result.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    return result

# 测试
root = TreeNode(1, left=TreeNode(2, right=TreeNode(5)), right=TreeNode(3, right=TreeNode(4)))
print(right_side_view(root))  # 输出：[1, 3, 4]